﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using HCQ2_Model.UploadModel;
using HCQ2_Common.Upload;
using System.IO;
using HCQ2_Model;
using HCQ2_Common;


namespace HCQ2UI_Logic
{
    /// <summary>
    ///  主页面控制器
    /// </summary>
    public class MainController:BaseLogic
    {
        #region 1.0 框架页首次加载 + ActionResult Index()
        [HttpGet]
        public ActionResult Index()
        {
            string userUrl = null;
            if (!string.IsNullOrEmpty(operateContext.Usr.user_img))
            {
                if (operateContext.Usr.user_img.IndexOf("http") < 0)
                    userUrl = operateContext.Usr.user_img.Replace("~", Request.ApplicationPath);
                else
                    userUrl = operateContext.Usr.user_img;
            }
            ViewBag.ownHead = userUrl;
            ViewBag.myUser = operateContext.Usr;
            ViewBag.sysVersion = operateContext.bllSession.T_ItemCode.FindSingle(s => s.item_code.Equals("sysVersion"))?.item_note;
            string logo= operateContext.bllSession.T_ItemCodeMenum.FindSingle(s => s.code_value.Equals("VRPcLogo"))?.code_note;
            ViewBag.logoUrl = (!string.IsNullOrEmpty(logo))
                ? logo.Replace("~", Request.ApplicationPath)
                : null;
            string lang = string.Empty;
            var cookie = Request.Cookies["Language"];
            if (cookie != null)
                lang = cookie.Value.ToString();
            else if (!string.IsNullOrEmpty(operateContext.Usr.lang))
            {
                if (operateContext.Usr.lang.Equals("cn-CN"))
                    lang = "cn";
                else if (operateContext.Usr.lang.Equals("en-US"))
                    lang = "en";
                else
                    lang = operateContext.Usr.lang;
            } else {
                lang = HCQ2UI_Helper.Session.SysPermissSession.sysLanguage;
                if (string.IsNullOrEmpty(lang))
                    lang = "cn";
            }
            ViewBag.sysLange = lang;
            return View("Index");
        }
        #endregion

        #region 1.1 首页 + ActionResult Index()
        [HttpGet]
        public ActionResult IndexPage()
        {
            return View("IndexPage");
        }
        #endregion

        #region 2.0 修改头像首次进入 + ActionResult HeadImgList()
        /// <summary>
        ///  2.0 修改头像首次进入
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        public ActionResult HeadImgList()
        {
            return View();
        }
        #endregion

        #region 2.1 上传头像 + ActionResult UploadImg()
        /// <summary>
        ///  2.1 上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImg()
        {
            Result result = new Result();
            result.avatarUrls = new List<string>();
            result.success = false;
            result.msg = "Failure!";
            // 取服务器时间+8位随机码作为部分文件名，确保文件名无重复。
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + uploadHelper.CreateRandomCode(8);

            #region 处理上传文件夹
            string path = Server.MapPath("~/UpFile/userImg");
            if (!Directory.Exists(path.ToString()))
                Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
            #endregion

            #region 处理原始图片

            // 默认的 file 域名称是__source，可在插件配置参数中自定义。参数名：src_field_name
            HttpPostedFileBase file = Request.Files["__source"];//__avatar1
                                                                // 如果在插件中定义可以上传原始图片的话，可在此处理，否则可以忽略。
            if (file != null)
            {
                //原始图片的文件名，如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg
                string sourceFileName = file.FileName;
                //原始文件的扩展名
                string sourceExtendName = sourceFileName.Substring(sourceFileName.LastIndexOf('.') + 1);
                //当前头像基于原图的初始化参数（只有上传原图时才会发送该数据，且发送的方式为POST），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
                //修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
                string initParams = Request.Form["__initParams"];
                result.sourceUrl = string.Format("~/UpFile/userImg/csharp_source_{0}.{1}", fileName, sourceExtendName);
                file.SaveAs(Server.MapPath(result.sourceUrl));
                result.sourceUrl += initParams;
                /*
				 * 可在此将 result.sourceUrl 储存到数据库，如果有需要的话。
				 * Save to database...
				 */

            }

            #endregion

            #region 处理头像图片

            //默认的 file 域名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names
            string[] avatars = new string[3] { "__avatar1", "__avatar2", "__avatar3" };
            int avatar_number = 1;
            int avatars_length = avatars.Length;
            for (int i = 0; i < avatars_length; i++)
            {
                file = Request.Files[avatars[i]];
                if (file == null)
                    break;
                string virtualPath = string.Format("~/UpFile/userImg/csharp_avatar{0}_{1}.jpg", avatar_number, fileName);
                result.avatarUrls.Add(virtualPath);
                file.SaveAs(Server.MapPath(virtualPath));
                /*
				 *	可在此将 virtualPath 储存到数据库，如果有需要的话。
				 *	Save to database...
				 */
                //判断原来是否有上传过文件，有则删除
                if (!string.IsNullOrEmpty(operateContext.Usr.user_img) && operateContext.Usr.user_img.IndexOf("http")<0)
                    System.IO.File.Delete(Server.MapPath(operateContext.Usr.user_img));
                operateContext.Usr.user_img = result.avatarUrls[0];
                operateContext.bllSession.T_User.Modify(operateContext.Usr, s => s.user_id == operateContext.Usr.user_id,
                    "user_img");
                avatar_number++;
            }

            #endregion

            //upload_url中传递的额外的参数，如果定义的method为get请将下面的context.Request.Form换为context.Request.QueryString

            result.success = true;
            result.msg = "Success!";
            //返回图片的保存结果（返回内容为json字符串，可自行构造，该处使用Newtonsoft.Json构造）
            return Json(result);
        }
        #endregion

        #region 2.2 获取当前登录用户对象
        /// <summary>
        ///  2.2 获取当前登录用户对象
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserInfo()
        {
            return operateContext.RedirectAjax(0, "", operateContext.Usr, "");
        }
        #endregion

        //************************3 新版头像上传****************************
        #region 3.0 修改头像首次进入 + ActionResult HeadPortrait()
        /// <summary>
        ///  修改头像首次进入
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        public ActionResult HeadPortrait()
        {
            return View();
        }
        #endregion

        #region 3.1 上传头像 + ActionResult UploadPicBase()
        /// <summary>
        ///  上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadPicBase()
        {
            string o = RequestHelper.GetStrByName("image");
            if (string.IsNullOrEmpty(o))
                return operateContext.RedirectAjax(1, "图像数据为空！", "", "");
            string picName = Guid.NewGuid().ToString().Replace("-", ""), //新名称
                prefixStr = o.Split(';')[0].Split('/')[1];//后缀扩展
            #region 处理上传文件夹
            string path = Server.MapPath($"~/UpFile/userImg/{operateContext.Usr.user_name}");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);//文件夹不存在则创建
            #endregion
            string virtualPath = $"~/UpFile/userImg/{operateContext.Usr.user_name}";
            byte[] picByte = Convert.FromBase64String(o.Split(',')[1]);//base64位图片数据
            string tempName = ImageHelper.CreateImageFromBytes(Server.MapPath(virtualPath), picName, picByte, prefixStr);

            //判断原来是否有上传过文件，有则删除
            if (!string.IsNullOrEmpty(operateContext.Usr.user_img) && operateContext.Usr.user_img.IndexOf("http")<0 && System.IO.File.Exists(Server.MapPath(operateContext.Usr.user_img)))
                System.IO.File.Delete(Server.MapPath(operateContext.Usr.user_img));
            string tempUrl = virtualPath + $"/{picName}.{prefixStr}";
            operateContext.Usr.user_img = tempUrl;
            operateContext.bllSession.T_User.Modify(operateContext.Usr, s => s.user_id == operateContext.Usr.user_id, "user_img");
            return operateContext.RedirectAjax(0, "头像上传成功！", tempUrl, "");
        }
        #endregion

        //************************4 系统语言设置****************************
        #region 4.0 系统语言设置 + ActionResult SaveChangeLanuage()
        /// <summary>
        ///  系统语言设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HCQ2_Common.Attributes.Skip]
        public ActionResult SaveChangeLanuage()
        {
            string lang = RequestHelper.GetStrByName("lang");
            if (string.IsNullOrEmpty(lang))
                lang = "zh";
            try {
                LangHelper.Init(lang,true);
            } catch (Exception e) { lang = "zh"; throw e; }
            if (operateContext.Usr != null)
            {
                operateContext.bllSession.T_User.Modify(new T_User { lang = lang }, s => s.user_id == operateContext.Usr.user_id, "lang");
                operateContext.Usr.lang = lang;
            }
            //HttpCookie _cookie = new HttpCookie("Language", lang);
            //_cookie.Expires = DateTime.Now.AddDays(1);
            //Response.Cookies.Add(_cookie);
            return operateContext.RedirectAjax(0, "系统语言设置成功！", "", "");
        }
        #endregion

        #region 4.1 获取系统选择语言对象json
        /// <summary>
        ///  获取系统选择语言对象json
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSysLanguage()
        {
            //Language lange;
            //System.Resources.ResourceManager rs = new System.Resources.ResourceManager("Resources.Language", typeof(Language).Assembly);
            return operateContext.RedirectAjax(0, "", "", "");
        }
        #endregion

        //************************5 Logo上传****************************
        #region 5 上传Logo + ActionResult UploadLogo()
        /// <summary>
        ///  上传Logo、或 下拉图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadLogo()
        {
            int item_id = RequestHelper.GetIntByName("item_id"),
                root = RequestHelper.GetIntByName("root");//0：根，1：子节点
            #region 字典下拉图片
            if (item_id > 0)
            {
                //判断字典下拉项数据真实性
                var item = root == 0 ? operateContext.bllSession.T_ItemCode.FindSingle(s => s.item_id == item_id) : null;
                var itemCode = root > 0 ? operateContext.bllSession.T_ItemCodeMenum.FindSingle(s => s.code_id == item_id) : null;
                if (null==item && null==itemCode)
                    return operateContext.RedirectAjax(1, "字典值数据异常！", "", "");
                string picName = Guid.NewGuid().ToString().Replace("-", ""), //新名称
                   picUrl = string.Empty;
                HttpPostedFileBase file = Request.Files["logo_img"];
                if (file == null)
                    return operateContext.RedirectAjax(1, "图像数据为空！", "", "");
                string virtualPath = $"~/uploadFile/LibraryFile/Images";
                #region 处理图片文件夹
                string path = Server.MapPath(virtualPath);
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);//文件夹不存在则创建
                #endregion

                #region 处理头像图片
                picUrl = virtualPath + $"/{picName}.jpg";
                file.SaveAs(Server.MapPath(picUrl));
                //判断原来是否有上传过文件，有则删除
                if (root > 0)
                {
                    //子节点
                    if (!string.IsNullOrEmpty(itemCode.logoUrl) && System.IO.File.Exists(Server.MapPath(itemCode.logoUrl)))
                        System.IO.File.Delete(Server.MapPath(itemCode.logoUrl));
                    itemCode.logoUrl = picUrl;
                    operateContext.bllSession.T_ItemCodeMenum.Modify(itemCode, s => s.code_id == item_id, "logoUrl");
                }
                else
                {
                    //根节点
                    if (!string.IsNullOrEmpty(item.logoUrl) && System.IO.File.Exists(Server.MapPath(item.logoUrl)))
                        System.IO.File.Delete(Server.MapPath(item.logoUrl));
                    item.logoUrl = picUrl;
                    operateContext.bllSession.T_ItemCode.Modify(item, s => s.item_id == item_id, "logoUrl");
                }
                return operateContext.RedirectAjax(0, "字典图片上传成功！", picUrl, "");
                #endregion
            }
            #endregion

            #region Logo
            else
            {
                var logo = operateContext.bllSession.T_ItemCodeMenum.FindSingle(s => s.code_value.Equals("VRPcLogo"));
                if (logo == null)
                    return operateContext.RedirectAjax(1, "字典：软件logo项不存在，代码为：SoftLogo！", "", "");
                string picName = Guid.NewGuid().ToString().Replace("-", ""), //新名称
                   picUrl = string.Empty;
                HttpPostedFileBase file = Request.Files["logo_img"];
                if (file == null)
                    return operateContext.RedirectAjax(1, "图像数据为空！", "", "");
                string virtualPath = $"~/UpFile/Logo/{operateContext.Usr.user_name}";
                #region 处理图片文件夹
                string path = Server.MapPath(virtualPath);
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);//文件夹不存在则创建
                #endregion

                #region 处理头像图片
                picUrl = virtualPath + $"/{picName}.jpg";
                file.SaveAs(Server.MapPath(picUrl));
                //判断原来是否有上传过文件，有则删除
                if (!string.IsNullOrEmpty(logo.code_note) && System.IO.File.Exists(Server.MapPath(logo.code_note)))
                    System.IO.File.Delete(Server.MapPath(logo.code_note));
                logo.code_note = picUrl;
                operateContext.bllSession.T_ItemCodeMenum.Modify(logo, s => s.code_id == logo.code_id, "code_note");
                return operateContext.RedirectAjax(0, "VR后台Logo上传成功！", picUrl, "");
                #endregion
            }
            #endregion
        }
        #endregion
    }
}